from langchain.tools import tool
from langchain_core.messages import HumanMessage, AIMessage, ToolMessage
from langchain_deepseek import ChatDeepSeek
import json
import warnings
warnings.filterwarnings("ignore", category=DeprecationWarning)

llm = ChatDeepSeek(
    model="deepseek-chat",  # 模型名称
    temperature=0,         # 控制生成随机性(0-1)
    max_tokens=None,       # 最大输出token数
    timeout=None,          # 超时设置
    max_retries=2,         # 失败重试次数
    api_key="sk-XXXXXXXX"
)
@tool
def get_weather(location: str) -> str:
    """查询指定城市的天气"""
    # 模拟工具调用（实际可能是API请求）
    return f"{location}的天气：25℃，晴朗"

model_with_tools = llm.bind_tools([get_weather])

# 用户输入
user_message = HumanMessage(content="今天大连天气如何？")

# 模型返回工具调用请求
ai_message = model_with_tools.invoke([user_message])
print(ai_message)

# 检查是否需要调用工具
if "tool_calls" in ai_message.additional_kwargs:
    tool_call = ai_message.additional_kwargs["tool_calls"][0]
    tool_name = tool_call["function"]["name"]
    tool_args = json.loads(tool_call["function"]["arguments"])
    location = tool_args["location"]

    # 执行工具
    if tool_name == "get_weather":
        result = get_weather(location)
        print(result)
